<template>
	<view class="card contact-info">
		<view class="card-top">
			<view class="title">填写联系信息</view>
			<view class="tips">用于接收电子门票信息</view>
		</view>
		<InfoDisplay
			label="联系人"
			v-model="contactInfo"
			type="contact"
			:show-id-type="false"
			:show-name="tourist_contact_rule?.contact_require_name"
			:show-id="tourist_contact_rule?.contact_require_id_value"
			:show-mobile="tourist_contact_rule?.contact_require_mobile"
			@open-popup="openPopup"
		/>
		<TouristContact
			type="contact"
			:show="show"
			@contact-info-change="handleContactInfoChange"
			@close-popup="closePopup"
		/>
	</view>
</template>

<script setup lang="ts">
import type { TouristContactRule } from "@/types/ticket"

interface TouristInfoProps {
	tourist_contact_rule: TouristContactRule
}

import { ref, onMounted, onUnmounted } from "vue"
import type { ContactsInfo } from "@/types/ticket"
import InfoDisplay from "./info-display.vue"
import TouristContact from "./tourist-contact.vue"

const show = ref(false)
const id = ref()
const contactInfo = ref<Partial<ContactsInfo> | null>(null)

defineProps<TouristInfoProps>()

defineExpose({
	contactInfo,
})

const openPopup = (num: number) => {
	id.value = num

	show.value = true
}

const closePopup = () => {
	id.value = undefined

	show.value = false
}

const handleContactInfoChange = (info: ContactsInfo | null) => {
	contactInfo.value = info
}

const handler = (info: ContactsInfo) => {
	if (!contactInfo.value) contactInfo.value = {}

	const keys = Object.keys(info) as Array<keyof ContactsInfo>

	for (let key of keys) {
		if (key !== "id_type" && contactInfo.value[key]) continue

		contactInfo.value[key] = info[key]
	}

	if (contactInfo.value.id_type && contactInfo.value.id_type !== 10) {
		contactInfo.value.id_value = ""
	}
}

onMounted(() => {
	uni.$on("first-tourist-info-change", handler)
})

onUnmounted(() => {
	uni.$off("first-tourist-info-change", handler)
})
</script>

<style lang="scss" scoped>
@import "../ticket/index.scss";

.contact-info {
	padding-bottom: 0;
}

.card-top {
	display: flex;
	align-items: center;

	.tips {
		margin-left: 8rpx;
		font-size: 24rpx;
		color: #86909c;
		line-height: 34rpx;

		.number {
			color: #bc8400;
		}
	}
}

.title {
	font-weight: 600;
	font-size: 32rpx;
	color: rgba(0, 0, 0, 0.9);
	line-height: 52rpx;
}
</style>
